// 作品选择窗口
import bindAll from 'lodash.bindall';
import PropTypes from 'prop-types';
import React from 'react';
import classNames from 'classnames';
import Filter from '../components/filter/filter.jsx';
import Divider from '../components/divider/divider.jsx';
import TagButton from './tag-button.jsx';
import Spinner from '../components/spinner/spinner.jsx';

import {Button, Card} from 'antd';
const {Meta} = Card;

import Modal from '../containers/modal.jsx'; // 选择窗口组件
import {getMyProjectLibrary, requestShareProject} from '../session-api';
import styles from './project-library.css';

class ProjectLibrary extends React.Component {
    constructor (props) {
        super(props);
        bindAll(this, [
            'handleClose',
            'handleFilterChange',
            'handleFilterKeyUp',
            'handleFilterClear',
            'handleTagClick',
            'handleOnScroll',
            'handleItemSelect',
            'setFilteredDataRef',
            'handleShareProject',
            'handleUnShareProject',
            'handleGetMoreItem'
        ]);
        this.state = {
            isSearch: false, // 开始搜索
            isEnterSearched: false, // 是否已经通过回车搜索过：在未回车搜索过时，直接清空搜索框时，不必去取分类的全部
            filterQuery: '',
            selectedTag: 100,
            projects: [], // projects.length 已获取的作品数，用于流方式加载
            isOver: false, // 是否已获取了分类下的全部作品
            loading: true // 是否已加载完
        };
    }
    componentWillMount (){
        this.getItemList(true); // 加载完后，第一次获取作品列表

    }
    componentDidUpdate (prevProps, prevState) {
        if (prevState.selectedTag !== this.state.selectedTag || this.state.isSearch) {
            this.getItemList(true);
        }
    }
    // 获取作品列表
    getItemList (newProjects) {
        // console.info("当前状态值：", this.state);
        if (newProjects) { // 只有滚动到底时，才不清空已获取的作品列表
            this.setState({projects: [], isOver: false});
        }

        if (this.state.isSearch) {
            this.setState({isSearch: false});
        }

        if (this.state.isOver) {
            return;
        }
        
        // 组件获取作品条件
        //     f: 搜索字符串
        //     t: 分类
        //     l: 已经获取的作品数
        //     n: 每次获取的作品数，默认为20个
        const searchParam = `f=${this.state.filterQuery}&&t=${this.state.selectedTag}&&l=${this.state.projects.length}&n=20`;
        getMyProjectLibrary(searchParam).then(res => {
            this.setState({loading: false}); 
            
            if (res.data.length < 20) {
                this.setState({isOver: true});
            }

            if (newProjects){
                this.setState({projects: res.data});
            } else {
                this.setState({projects: this.state.projects.concat(res.data)});
            }
        });
    }

    
    // 关闭窗口
    handleClose () {
        this.props.onRequestClose();
    }

    // 切换标签
    handleTagClick (type) {
        if (this.state.selectedTag != type){
            this.setState({filterQuery: '', isEnterSearched: false, selectedTag: type, projects: [], isOver: false, loading: true});
        }
    }

    // 搜索：输入字符串
    handleFilterChange (event) {
        this.setState({filterQuery: event.target.value});
    }
    // 搜索：按回车时开始搜索
    handleFilterKeyUp (event) {
        if (event.keyCode === 13 && event.target.value.length > 0) {
            this.setState({isSearch: true, isEnterSearched: true, projects: [], isOver: false, loading: true}); // 触发搜索
        }
    }
    // 搜索：清空字符串
    handleFilterClear () {
        this.setState({filterQuery: ''});
        if (this.state.isEnterSearched) { // 在未回车搜索过时，直接清空搜索框时，不必去取分类的全部
            this.setState({isSearch: true, isEnterSearched: false, projects: [], isOver: false, loading: true});
        }
    }

    // 绑定组件变量，为监听页面滚动
    setFilteredDataRef (ref) {
        this.filteredDataRef = ref;
    }
    // 监听页面滚动，到底后，再次自动加载作品
    handleOnScroll () {
        if (this.filteredDataRef) {
            const contentScrollTop = this.filteredDataRef.scrollTop; // 滚动条距离顶部
            const clientHeight = this.filteredDataRef.clientHeight; // 可视区域
            const scrollHeight = this.filteredDataRef.scrollHeight; // 滚动条内容的总高度
            
            if ((contentScrollTop > 0) && ((contentScrollTop + clientHeight) >= scrollHeight)) {
                if (!this.state.isOver) {
                    this.getItemList(false); // 继续获取数据的方法
                }
                // console.error('已到底');
            }
        }
    }
    // 手动点击按钮，继续获取数据的方法
    handleGetMoreItem () {
        if (!this.state.isOver) {
            this.getItemList(false);
        }
    }

    // 分享作品
    handleShareProject (projectId, index) {
        requestShareProject(projectId, 1).then(
            body => {
                 if (body.status == 'ok') {
                    if (this.state.selectedTag == 100){
                        this.state.projects[index].state = 1;
                        this.setState({projects: this.state.projects});
                    } else if (this.state.selectedTag == 0){
                        this.state.projects.splice(index, 1);
                        this.setState({projects: this.state.projects}); 
                    }
                }
            }, err => {}
        );
    }
    // 取消分享
    handleUnShareProject (projectId, index) {
        requestShareProject(projectId, 0).then(
            body => {
                 if (body.status == 'ok') {
                    if (this.state.selectedTag == 100){
                        this.state.projects[index].state = 0;
                        this.setState({projects: this.state.projects});
                    } else if (this.state.selectedTag == 1){
                        this.state.projects.splice(index, 1);
                        this.setState({projects: this.state.projects}); 
                    }
                }
            }, err => {}
        );
    }
    // 打开作品
    handleItemSelect (projectId) {
        const newHash = '#' + projectId;;
        if (window.location.hash == newHash){
            this.handleClose();
        } else {
            window.location.hash = newHash;
            history.pushState('', '', window.location.pathname + newHash);
        }

    }

    render () {
        return (
            <Modal
                fullScreen
                contentLabel="我的作品"
                id="ProjectLibrary"
                onRequestClose={this.handleClose}
            >

                {/* 搜索、分类部分 */}
                <div className={styles.filterBar}>
                    <Filter
                        className={classNames(styles.filterBarItem, styles.filter)}
                        filterQuery={this.state.filterQuery}
                        inputClassName={styles.filterInput}
                        placeholderText="搜索"
                        onChange={this.handleFilterChange}
                        onClear={this.handleFilterClear}
                        onKeyUp={this.handleFilterKeyUp}
                    />

                    <Divider className={classNames(styles.filterBarItem, styles.divider)} />

                    <div className={styles.tagWrapper}>
                        {[
                            {tag: "全部作品", type: 100},
                            {tag: "未分享", type: 0},
                            {tag: "已分享", type: 1}
                            // ,{tag: "收藏的作品", type: 200}
                        ].map((tag, index) => (
                            <TagButton
                                active={this.state.selectedTag === tag.type}
                                className={classNames(styles.filterBarItem, styles.tagButton)}
                                key={`tag-button-${index}`}
                                onClick={()=>this.handleTagClick(tag.type)}
                                tag={tag.tag}
                            />
                        ))}
                    </div>
                </div>

                <div
                    className={classNames(styles.libraryScrollGrid, styles.withFilterBar)}
                    ref={this.setFilteredDataRef}
                    onScrollCapture={this.handleOnScroll}
                >
                    {this.state.loading ? (
                        <div className={styles.spinnerWrapper}>
                            <Spinner
                                large
                                level="primary"
                            />
                        </div>
                    ) : (<>
                        {(this.state.projects.length == 0)&&(
                            <div className={styles.spinnerWrapper}>
                                <div className={styles.spanBox}>空</div>
                            </div>
                        )}

                        {this.state.projects.map((item, index) => (
                            <Card
                                hoverable
                                className={styles.ItemCard}
                                style={{width: 200, margin: 6, borderRadius: 6}}
                                cover={<img src={`/scratch_slt/${item.id}`} style={{width: 180, margin: 10}}/>}
                                key={index}
                                onClick={()=>this.handleItemSelect(item.id)}
                            >
                                <Meta
                                    title={item.title}
                                    description={item.time.slice(0, 10)}
                                />
                                <div style={{marginTop: 12}}>
                                    {(item.state==0)?(
                                        <Button onClick={(e)=>{e.stopPropagation(); this.handleShareProject(item.id, index)}} style={{width:152}}>分享作品</Button>
                                    ) : (
                                        <Button onClick={(e)=>{e.stopPropagation(); this.handleUnShareProject(item.id, index)}} style={{width:152}}>取消分享</Button>
                                    )}
                                    {/* <Button onClick={(e)=>{e.stopPropagation(); this.handleDeleteProject(item.id, index)}} style={{width:152}}>删除</Button> */}
                                </div>
                            </Card>
                        ))}
                        
                        {!this.state.isOver && (
                            <div
                                className={styles.spinnerWrapper1}
                                onClick={this.handleGetMoreItem}
                            >
                                <div className={styles.spanBox}>点我可继续</div>
                            </div>
                        )}

                    </>)}
                </div>
            </Modal>
        );
    }
}

ProjectLibrary.propTypes = {
    onRequestClose: PropTypes.func
};

export default ProjectLibrary;
